package com.examiner.controller;

import com.examiner.bean.Do.RoleMenuDo;
import com.examiner.bean.Manager;
import com.examiner.page.QueryInfo;
import com.examiner.result.EmptyObject;
import com.examiner.result.Result;
import com.examiner.service.ManagerService;
import com.examiner.service.RoleMenuService;
import com.examiner.token.JwtUtil;
import org.hibernate.Session;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
@RequestMapping("/manager")
public class ManagerController {

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @Resource
    private ManagerService managerService;

    @Resource
    private RoleMenuService roleMenuService;

    @PersistenceContext
    private EntityManager entityManager;

    /*
    *  Login 登录
    *   code: 1001     msg: 判断该用户名已存在
    *   code: 1002     msg: 判断该用户名不存在
    *   code: 1003      msg: 登录密码错误
    *   code: 1004     msg: 修改密码失败
    * */
    @PostMapping("/login")
    public Result<Object> login(@RequestBody Manager manager, HttpServletResponse response){
        System.out.println(passwordEncoder.encode(manager.getPassword()));
        // 判断用户是否存在   TODO 在前端加用户名验证
        Manager managerByUserName = managerService.findManagerByUserName(manager.getUserName());
        if (managerByUserName == null){
            // 该用户不存在
            return Result.RESULT(1002,"该用户不存在",false,null);
        }
        // 验证密码是否正确
        boolean matches = passwordEncoder.matches(manager.getPassword(),managerByUserName.getPassword());
        //System.out.println(manager.getManagerPassword()+":"+managerByUserName.getManagerPassword()+"-->"+matches);
        if (!matches){
            // 密码不匹配,登录失败
            return Result.RESULT(1003,"密码错误，登录失败",false,null);
        }
        Session session = entityManager.unwrap(org.hibernate.Session.class);
        session.evict(managerByUserName);
        // 生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put("userName", managerByUserName.getUserName());
        claims.put("role", "manager");
        String token = JwtUtil.createJWT(UUID.randomUUID().toString(), "manager", null, claims);
        // 添加头部信息
        response.addHeader("token", token);
        //System.out.println(token);
        managerByUserName.setPassword("");
        Map<String, Object> data = new HashMap<>();
        data.put("user",managerByUserName);
        data.put("token",token);
        List<RoleMenuDo> roleList = roleMenuService.getRoleList(managerByUserName.getRole());
        data.put("roleList",roleList);
        // 登录成功，返回一个管理员manager
        return Result.RESULT(200,"登录成功",true,data);
    }


    /**
     * 根据用户名查询管理员
     * code: 1001     msg: 判断该用户名已存在
     * @param managerUserName
     * @return Result
     */
    @PostMapping("/findManager/{managerUserName}")
    public Result<Manager> findManagerByManagerUserName(@PathVariable("managerUserName")String managerUserName){
        Manager managerByUserName = managerService.findManagerByUserName(managerUserName);
        // 判断该用户名是否被使用
        if (managerByUserName == null){
            return Result.RESULT(1001,"该用户名不存在",false,null);
        }
        managerByUserName.setPassword("");
        return Result.RESULT(200,"该用户名存在",true,managerByUserName);
    }

    /* 根据id删除 */
    @DeleteMapping("/delManager/{managerId}")
    public Result<EmptyObject> deleteManager(@PathVariable("managerId")Integer managerId){
        QueryInfo queryInfo = new QueryInfo();
        List<Manager> managerList;
        try{
            queryInfo.setPageNum(1);
            queryInfo.setPageSize(5);
            queryInfo.setQuery("");
            managerList = managerService.getManagerList(queryInfo);
            if (managerList.size() <= 1){
                return Result.RESULT(201,"删除失败,仅剩一名管理员",true,null);
            }
            managerService.deleteManager(managerId);
        }catch (Exception e){
            return Result.RESULT(201,"删除失败",true,null);
        }
        return Result.RESULT(200,"删除成功",true,null);
    }


    /* 新增
    * code: 1002     msg: 改管理员添加失败
    * */
    @PostMapping("/addManager")
    public Result<EmptyObject> addManager(@RequestBody Manager manager){
        // 对密码进行加密
        manager.setPassword(passwordEncoder.encode(manager.getPassword()));
        manager.setRole("manager");
        manager.setState(true);
        managerService.saveManager(manager);
        return Result.SUCCESS(EmptyObject.empty);
    }

    /* 修改 用户信息*/
    @PutMapping("/changeUserInfo")
    public Result<EmptyObject> updateManager(@RequestBody Manager manager){
        Manager managerById = managerService.findOne(manager.getId());
        // 判断该用户名是否被使用
        if (managerById == null){
            return Result.RESULT(1002,"该用户名不存在",false,null);
        }
        if (!manager.getPassword().equals(managerById.getPassword())){
            manager.setPassword(passwordEncoder.encode(manager.getPassword()));
        }
        managerService.saveManager(manager);
        return Result.SUCCESS(EmptyObject.empty);
    }

    /**
     * 检查原密码是否正确
     * @param oldPassword
     * @return
     */
    @PostMapping("/checkPassword/{id}")
    public Result<EmptyObject> checkPassword(@PathVariable("id")Integer id,
                                             @RequestBody String oldPassword){
        Manager one = managerService.findOne(id);
        // 验证密码
        if (one == null){
            // 该用户不存在
            return Result.RESULT(1002,"该用户不存在",false,null);
        }
        // 验证密码是否正确
        boolean matches = passwordEncoder.matches(oldPassword,one.getPassword());
        if (!matches){
            return Result.RESULT(1003,"密码错误",false,null);
        }
        return Result.SUCCESS(EmptyObject.empty);
    }

    /**
     * 修改密码
     */
    @PostMapping("/updatePassword/{id}")
    public Result<EmptyObject> updatePassword(@PathVariable("id")Integer id,
                                              @RequestBody String newPassword){
        String encodePsw = passwordEncoder.encode(newPassword);
        Boolean aBoolean = managerService.updateManagerPassword(id,encodePsw );
        if (!aBoolean) return Result.RESULT(1004,"修改密码失败",false,null);
        return Result.SUCCESS(EmptyObject.empty);
    }


    /* 带条件 分页查询  manager 列表*/
    @PostMapping("/getManagerList")
    public Result<Object> getManagerList(@RequestBody QueryInfo queryInfo){
        //System.out.println("getManagerList");
        Map<String, Object> data = new HashMap<>();
        List<Manager> managerList =  managerService.getManagerList(queryInfo);
        int total = managerService.getTotal(queryInfo.getQuery());
        //managerList.forEach(manager -> manager.setPassword(""));
        data.put("total",total);
        data.put("managerList",managerList);
        return Result.SUCCESS(data);
    }



}
